using UIFramework.Core;
using UnityEngine;

namespace UIFramework.Panel
{
    /// <summary>
    /// 这个Layer层是控制面板的
    /// 面板是界面的一种，没有历史记录，没有队列
    /// 允许多个一同显示
    /// 比如小地图，体力槽等等常驻的
    /// </summary>
    public class PanelUILayer : UILayer<IPanelController>
    {
        [SerializeField]
        [Tooltip("优先级并行层的设置，注册到此层的面板将根据优先级重新归属到不同的并行对象")]
        private PanelPriorityLayerList priorityLayers = null;
        
        public override void ShowScreen(IPanelController screen)
        {
            screen.Show();
        }

        public override void ShowScreen<TProps>(IPanelController screen, TProps properties)
        {
            screen.Show(properties);
        }

        public override void HideScreen(IPanelController screen)
        {
            screen.Hide();
        }

        public override void ReparentScreen(IScreenController controller, Transform screenTransform)
        {
            var ctl = controller as IPanelController;
            if (ctl != null)
            {
                ReparentToParaLayer(ctl.Priority, screenTransform);
            }
            else
            {
                base.ReparentScreen(controller, screenTransform);
            }
        }
        
        /// <summary>
        /// 面板是否显示
        /// </summary>
        /// <param name="screen">界面id</param>
        /// <returns></returns>
        public bool IsPanelVisible(string screen)
        {
            IPanelController panel;
            if (registeredScreens.TryGetValue(screen, out panel))
            {
                return panel.IsVisible;
            }
            return false;
        }
        
        /// <summary>
        /// 根据面板层级设置父节点
        /// </summary>
        /// <param name="priority">面板层级</param>
        /// <param name="screenTransform">需要设置的Transform</param>
        private void ReparentToParaLayer(PanelPriority priority, Transform screenTransform)
        {
            Transform trans;
            // 查找层级对应的父节点
            if (!priorityLayers.ParaLayerLookup.TryGetValue(priority, out trans))
            {
                // 找不到直接设置在当前节点下
                trans = transform;
            }
            
            screenTransform.SetParent(trans, false);
        }
    }
}